package com.lyc.controller.user;

import com.lyc.DTO.UserDTO;
import com.lyc.DTO.AdminUserDTO;
import com.lyc.pojo.Result;
import com.lyc.pojo.User;
import com.lyc.service.UserService;
import com.lyc.utils.JwtUtil;
import com.lyc.utils.Md5Util;
import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController// 表示该类是一个控制器
@Validated //  开启参数校验
@CrossOrigin // 添加这一行允许跨域
@RequestMapping("/user")
public class UserController {
    @Autowired //  自动注入
    private UserService userService;

    // 注入redis
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    // 用户注册
    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^.{2,}$") String username,
                           @Pattern(regexp = "^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{5,16}$") String password,
                           String avatar){
        //查询用户名是否已存在
        User u =userService.findByUserName(username);
        if(u == null){
            //没有占用
            //注册
            userService.register(username,password,avatar);
            return Result.success();
        }else{
            return Result.error("用户名已占用");
        }
    }

    //登录
    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^.{2,}$") String username,
                                @Pattern(regexp = "^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{5,16}$") String password) throws Exception {
        //根据用户名查询用户
        User u =userService.findByUserName(username);
        //判断用户是否存在
        if(u == null){
            return Result.error("用户名不存在");
        }
        //密码正确
        if(Md5Util.getMD5String(password).equals(u.getPassword())){
            //登录成功
            Map<String,Object> claims = new HashMap<>();
            claims.put("id",u.getId());
            claims.put("username",u.getUsername());
            String token = JwtUtil.genToken(claims);
            //把token存储到redis
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            operations.set(token,token,1, TimeUnit.HOURS);
            System.out.println("Token 已存入 Redis: " + token);

            return Result.success(token);
        }
        return Result.error("密码错误");
    }

    //获取全部用户列表
    @GetMapping("/all")
    public Result<List<User>> getAllUser(){
        List<User> users = userService.getAllUser();
        return Result.success(users);
    }

    //获取用户信息
    @GetMapping("/info")
    public Result<User> info(@RequestHeader(name = "Authorization") String token){
        //从redis中获取token
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        String tokenRedis = operations.get(token);
        if(tokenRedis == null){
            return Result.error("未登录");
        }
        Map<String, Object> claims = JwtUtil.parseToken(tokenRedis);

        String username = (String) claims.get("username");
        //获取用户信息
        User u =userService.findByUserName(username);
        return Result.success(u);
    }

    //获取帖子用户信息--根据id
    @GetMapping("/infoById")
    public Result<User> infoById(Integer userId){
        User u =userService.findById(userId);
        return Result.success(u);
    }

    //获取用户帖子数量
    @GetMapping("/postCount")
    public Result<Integer> getPostCount(Integer userId){
        Integer count = userService.getPostCount(userId);
        return Result.success(count);
    }

    //修改头像
    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestBody @URL String avatar){
        userService.updateAvatar(avatar);
        return Result.success();
    }

    //修改用户信息
    @PutMapping("/updateInfo")
    public Result update(@RequestBody @Validated UserDTO userDTO ){
        userService.updateById(userDTO);
        return Result.success();
    }
    
    // 管理员修改用户信息
    @PutMapping("/admin/updateInfo")
    public Result updateByAdmin(@RequestBody @Validated AdminUserDTO adminUserDTO) {
        try {
            userService.updateUserInfoByAdmin(adminUserDTO);
            return Result.success("用户信息更新成功");
        } catch (Exception e) {
            return Result.error("用户信息更新失败: " + e.getMessage());
        }
    }
    
    // 批量更新用户状态（通常为管理员操作）
    @PutMapping("/batchUpdateStatus")
    public Result batchUpdateStatus(@RequestBody Map<String, Object> request) {
        try {
            @SuppressWarnings("unchecked")// 用于忽略类型检查
            List<Integer> userIds = (List<Integer>) request.get("userIds");
            String status = (String) request.get("status");
            
            if (userIds == null || userIds.isEmpty()) {
                return Result.error("用户ID列表不能为空");
            }
            
            if (status == null || status.isEmpty()) {
                return Result.error("状态不能为空");
            }
            
            userService.batchUpdateUserStatus(userIds, status);
            return Result.success("用户状态更新成功");
        } catch (Exception e) {
            return Result.error("用户状态更新失败: " + e.getMessage());
        }
    }
    
    // 批量更新用户角色（通常为管理员操作）
    @PutMapping("/batchUpdateRole")
    public Result batchUpdateRole(@RequestBody Map<String, Object> request) {
        try {
            @SuppressWarnings("unchecked")
            List<Integer> userIds = (List<Integer>) request.get("userIds");
            String role = (String) request.get("role");
            
            if (userIds == null || userIds.isEmpty()) {
                return Result.error("用户ID列表不能为空");
            }
            
            if (role == null || role.isEmpty()) {
                return Result.error("角色不能为空");
            }
            
            // 验证角色值是否合法
            if (!"user".equals(role) && !"admin".equals(role)) {
                return Result.error("角色值不合法，只能为'user'或'admin'");
            }
            
            userService.batchUpdateUserRole(userIds, role);
            return Result.success("用户角色更新成功");
        } catch (Exception e) {
            return Result.error("用户角色更新失败: " + e.getMessage());
        }
    }

    // 批量更新用户认证状态（通常为管理员操作）
    @PutMapping("/batchUpdateVerification")
    public Result batchUpdateVerification(@RequestBody Map<String, Object> request) {
        try {
            @SuppressWarnings("unchecked")
            List<Integer> userIds = (List<Integer>) request.get("userIds");
            Boolean isVerified = (Boolean) request.get("isVerified");
            if (userIds == null || userIds.isEmpty()) {
                return Result.error("用户ID列表不能为空");
            }

            if (isVerified == null) {
                return Result.error("认证状态不能为空");
            }

            userService.batchUpdateUserVerification(userIds, isVerified);
            return Result.success("用户认证状态更新成功");
        } catch (Exception e) {
            return Result.error("用户认证状态更新失败: " + e.getMessage());
        }
    }
    
    // 删除用户（支持单个或批量删除）
    @DeleteMapping("/delete")
    public Result deleteUsers(@RequestBody Map<String, Object> request) {
        try {
            @SuppressWarnings("unchecked")
            List<Integer> userIds = (List<Integer>) request.get("userIds");
            
            if (userIds == null || userIds.isEmpty()) {
                return Result.error("用户ID列表不能为空");
            }
            userService.deleteUsers(userIds);
            return Result.success("用户删除成功");
        } catch (Exception e) {
            return Result.error("用户删除失败: " + e.getMessage());
        }
    }
}